package com.ibm.cps.model;

import java.util.HashMap;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.message.MessageFields;
import com.ibm.cps.message.validation.IProcessorValidator;
import com.ibm.cps.message.validation.NodeRedValidator;
import com.ibm.cps.message.validation.SQLValidator;
import com.ibm.factories.DataSourceFactory;
import com.ibm.factories.PublishProcessorFactory;
import com.ibm.util.ErrorCode;
import com.ibm.util.SchemaCache;
import com.ibm.util.exception.CPSException;

public class AdapaterFactory {

	private static HashMap<String, IProcessorValidator> source2Validator = new HashMap<String, IProcessorValidator>();

	static {
		source2Validator.put(MessageFields.NODERED, new NodeRedValidator());
		source2Validator.put(MessageFields.PROCESSOR_GROUP_CONTENT, new SQLValidator());
	}

	public static IProcessorValidator getValidator(String type) {
		return source2Validator.get(type);
	}

	public static MetadataAdapter getAdapter(DataSourceFactory factory, PublishProcessorFactory publishFactory,
			String type) throws CPSException {
		if (type.equals("node-red")) {
			return new NodeRedJsonAdapter(factory, publishFactory);
		} else if (type.equals("sql")) {
			return new SQLAdapter(factory, SchemaCache.getInstace(), publishFactory);
		} else if (type.equals("rest")) {
			return new RestAdapter(factory, publishFactory);
		} else {
			throw new CPSException(ErrorCode.INVALID_INPUT_ERROR, "Error type " + type + " of adapter");
		}
	}

	public static void validate(String source, ObjectNode object) throws CPSException {
		if (source2Validator.get(source) != null) {
			source2Validator.get(source).validatePostMessage(object);
		}
	}
}
